import os
import time

import openai
from .model import Model
from ..utils import LOG


class OpenAIModel(Model):
    def __init__(self, model_name: str, api_key: str):
        self.model = model_name
        self.client = openai.OpenAI(
            api_key=os.getenv("OPENAI_API_KEY"),
        )

    def make_request(self, prompt):
        attempts = 0
        # 重试三次
        while attempts < 3:
            try:
                if self.model == 'gpt-3.5-turbo':
                    response = self.client.chat.completions.create(model=self.model, messages=[
                        {"role": "user", "content": prompt}
                    ])
                    LOG.debug(f'response {response}')
                    translation = response.choices[0].message.content.strip()
                else:
                    translation = ''
                return translation, True
            except openai.RateLimitError as e:
                attempts += 1
                if attempts < 3:
                    LOG.warning("Rate limit reached. Waiting for 60 seconds before retrying.")
                    time.sleep(60)
                else:
                    raise Exception("Rate limit reached. Maximum attempts exceeded.")
            except openai.APIConnectionError as e:
                # an underlying Exception, likely raised within httpx.            except requests.exceptions.Timeout as e:
                print("The server could not be reached")
                print(e.__cause__)
            except openai.APIStatusError as e:
                print("Another non-200-range status code was received")
                print(e.status_code)
                print(e.response)
            except Exception as e:
                raise Exception(f"发生了未知错误：{e}")
            return "", False
